<?php
/**
 * Created by PhpStorm.
 * User: 胥九庆
 * Date: 2023/01/05
 * Time: 14:08
 */
declare (strict_types=1);

namespace app\common\model;

use app\common\facade\Pay;
use app\common\tool\account\Account;

class CourseOrder extends Base
{
    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function getPayWayAttr($value)
    {
        return get_pay_way($value);
    }

    /**
     * 提交订单
     */
    public static function submit($param, $user): array
    {
        $info =  Course::where(['id' => $param['course_id'], 'is_del' => 0])->find();
        if (empty($info)) return ['code' => -1, 'msg' => '该课程不存在！'];
        if ($info->is_free != 2) return ['code' => -1, 'msg' => '该课程不需要支付'];
        if (!$info->price || $info->price <= 0) return ['code' => -1, 'msg' => '该课程金额有误'];
        $count = parent::where(['course_id' => $param['course_id'], 'uid' => $user->id, 'state' => 2, 'is_del' => 0])->count('id');
        if ($count > 0) return ['code' => -1, 'msg' => '您已购买过该课程'];
        parent::startTrans();
        try {
            $data = [
                'sn' => date('YmdHis').rand(100000, 999999).$user->id,
                'uid' => $user->id,
                'course_id' => $info->id,
                'title' => $info->title,
                'img' => $info->img,
                'total_amount' => $info->price,
                'real_amount' => $info->price,
                'rebate_uid' => $info->uid,
                'rebate_amount' => $info->rebate_amount,
                'is_del' => 1
            ];
            $new = parent::create($data);
            $data['id'] = $new->id;
            $method = isset($param['method'])? $param['method']: '';
            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return self::confirmPayment($data, $param['pay_way'], $method, $user);
    }

    /**
     * 确认支付
     */
    public static function confirmPayment($order, $pay_way, $method, $user): array
    {
        switch ($pay_way) {
            case "love_bean":
            case "chain_bean":
                if ($user->assets->$pay_way < $order['real_amount']) {
                    return ['code' => -1, 'msg' => '账户余额不足'];
                }
                return self::operation($order, $user, $pay_way);
            case "wechat":
                if (!in_array($method, ['JSAPI', 'APP'])) {
                    return ['code' => -1, 'msg' => '支付标识不存在'];
                }
                $notifyUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/time/callback/collegeWechat';
                //设置参数
                $wechat_pay = Pay::setDriver('WeChat')
                    ->basic('商学院-购买课程', $order['sn'], $order['real_amount'], $notifyUrl);
                if ($method == 'JSAPI') {
                    $wechat_pay->setOpenId($user->openid);
                }
                $options = $wechat_pay->create($method);
                return ['code' => 1, 'msg' => 'success', 'data' => $options];
            case "alipay":
                return ['code' => -1, 'msg' => '该支付方式暂未开放'];
            default:
                return ['code' => -1, 'msg' => '请选择支付方式'];
        }
    }

    /**
     * 支付完成后续操作
     */
    public static function operation($order, $user, $pay_way): array
    {
        parent::startTrans();
        try {
            //更改状态
            $data = [
                'pay_way' => $pay_way,
                'state' => 2,
                'pay_time' => time(),
                'is_del' => 0
            ];
            parent::update($data, ['id' => $order['id']]);
            //扣钱
            if (!in_array($pay_way, ['wechat', 'alipay'])) {
                Account::getInstance()->basics($user->id, $pay_way, $order['real_amount'], '购买商学院课程', '-')
                    ->createNormal($order['id']);
            }
            if ($order['rebate_amount'] > 0 && $order['rebate_uid']) {
                Account::getInstance()->basics($order['rebate_uid'], 'chain_bean', $order['rebate_amount'], '课程分润', '+')
                    ->createNormal($order['id']);
            }
            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '支付成功'];
    }
}